'''
print("定义函数")
print("打印问候语的简单函数，名为greet_user()")
def greet_user():
    """显示简单的问候语"""
    print("hello")
greet_user()

print("\n向函数传递信息")
print("让greet_user()在问候用户时以名字作为抬头")
def greet_user(username):
    print(f"hello,{username.title()}")
greet_user("jesse")


print("练习8.1：消息")
def display_message(topic):
    """指出本章的主题是什么"""
    print(f"the topic of this chapter is {topic}")
display_message("functions")

print("练习8.2：喜欢的书")
def favorite_book(title):
    print(f"one of my favorite book is {title}")
favorite_book("alice in wonderland")


print("传递实参：一，位置实参:要求实参的顺序与形参的顺序相同,顺序很重要；二，关键字实参:是传递函数的名值对，在实参中将名称和值关联起来")
print("位置实参")
print("显示宠物信息的函数，函数指出一个宠物属于哪种品种及叫什么名字，可调用函数多次")
def describe_pet(animal_type,pet_name):
    print(f"i have a {animal_type}")
    print(f"my {animal_type}'s name is {pet_name.title()}")
describe_pet("hamster","harry")
describe_pet("dog","willie")

print("关键字实参")
def describe_pet(animal_type,pet_name):
    print(f"i have a {animal_type}")
    print(f"my {animal_type} is {pet_name.title()}")
describe_pet(animal_type="hamster",pet_name="harry")
describe_pet(pet_name="harry",animal_type="hamster")

print("默认值：在编写函数时。可以给每个形参指定默认值")
print("如果调用函数时，发现描述的大多是小狗，就可将形参animal_type的默认值设置为“dog")
def describe_pet(pet_name,animal_type="dog"):
    """由于animal_type指定了默认值，无需通过实参来指定动物类型，
    因此函数调用只包含一个实参：宠物的名字，python依然将这个实参
    视为位置实参，这需要将pet-name放在形参列表开头"""
    print(f"i have a {animal_type}")
    print(f"my {animal_type} is {pet_name.title()}")
describe_pet("willie")
describe_pet(animal_type="hamster",pet_name="harry")#若不是小狗，可使用关键字实参


print("避免实参错误:当提供的实参多于或少于函数完成工作所需的实参数量时，将出现实参不匹配错误")
def describe_pet(animal_type,pet_name):
    print(f"i have a {animal_type}")
    print(f"my {animal_type}'s name is {pet_name.title()}")
describe_pet()#调用函数时未指定任何实参，会报错


print("练习8.3：T恤")
def make_shirt(size,print_word):
    print(f"the size and print on this t_shirt are {size} and {print_word}")
make_shirt("M","beautiful")
make_shirt(size="M",print_word="beautiful")
make_shirt(print_word="beautiful",size="M")


print("练习8.4：大号T恤")
def make_shirt(size,print_word="i love python"):
    print(f"the size and print on this t_shirt are {size} and '{print_word}'")
make_shirt("L")
make_shirt("L","hello world")


print("练习8.5：城市")
def describe_city(city,country="iceland"):
    print(f"{city.title()} is in {country.title()}")
describe_city("reykjavik")
describe_city("sichuan","china")
describe_city(country="china",city="shanghai")


print("返回值")
print("函数并非总是直接显示输出，它还可以处理一些数据，并返回一个或一组值。函数返回的值称为返回值")
print("返回简单的值")
print("接受名和姓并返回标准格式的姓名")
def get_formatted_name(first_name,last_name):
    """返回标准格式的姓名"""
    full_name=f"{first_name} {last_name}"
    return full_name.title()
musician=get_formatted_name("jimi","hendrix")
print(musician)


def get_formatted_name(first_name,last_name):
    """返回标准格式的姓名"""
    print(f"{first_name.title()} {last_name.title()}")
get_formatted_name("jimi","hendrix")


print("让实参变成可选的：可以使用默认值来让实参变成可选的")
print("拓展get_formatted_name()函数，在其增加中间名")
def get_formatted_name(first_name,middle_name,last_name):
    full_name=f"{first_name} {middle_name} {last_name}"
    return full_name.title()
musician=get_formatted_name("john","lee","hooker")
print(musician)

print("但不是所有人都有中间名，给中间名指定默认值（空字符串）")
def get_formatted_name(first_name,last_name,middle_name=""):
    if middle_name:
        full_name=f"{first_name} {middle_name} {last_name}"
    else:
        full_name=f"{first_name} {last_name}"
    return full_name.title()
musician=get_formatted_name("jimi","hendrix")
print(musician)
musician=get_formatted_name("jihn","hooker","lee")
print(musician)


print("返回字典")
print("函数可返回任何类型的值，包括列表和字典等较为复杂的数据结构")
def bulid_person(first_name,last_name):
    """返回一个字典，其中包含有关一个人的信息"""
    person={'first':first_name,'last':last_name}
    return person
musician=bulid_person('jimi','hendrix')
print(musician)



print("增加可选值，使其存储年龄")
def bulid_person(first_name,last_name,age=None):
    """返回一个字典，其中包含有关一个人的信息"""
    person={'first':first_name,'last':last_name}
    if age:
        person['age']=age
    return person
musician=bulid_person('jimi','hendrix',27)   #27换成age=27同样
print(musician)


print("结合使用函数和while循环")
print("尝试使用姓和名跟用户打招呼")
def get_formatted_name(first_name,last_name):
    """返回规范格式的姓名"""
    full_name=f"{first_name} {last_name}"
    return full_name.title()
#这是一个无限循环
while True:
    print("please tell me your name:")
    f_name=input('first_name:')
    l_name=input('last_name:')
    formatted_name=get_formatted_name(f_name,l_name)
    print(f"hello,{formatted_name}")


print("给以上定义退出途径")
def get_formatted_name(first_name,last_name):
    full_name=f"{first_name} {last_name}"
    return full_name.title()
while True:
    print("please tell me your name:")
    print("enter a 'q' at any time to quit")
    f_name=input('first_name:')
    if f_name == 'q':
        break
    l_name=input('last_name:')
    if l_name == 'q':
        break
    formatted_name=get_formatted_name(f_name,l_name)
    print(formatted_name)


print("练习8.6：城市名")

def sum(x,y):
    f=x+y
    print(f)
    return f

def city_country(city,country):
    print(f"{city.title()} , {country.title()}")
city_country('cichuan','china')
city_country(city='shanghai',country='china')
city_country(country='china',city='guangdong')

def city_country(city,country):
    cc= f"{city.title()} , {country.title()}"
    return cc
a=city_country('cichuan','china')
b=city_country(city='shanghai',country='china')
c=city_country(country='china',city='guangdong')
print(f"{a},\n{b},\n{c}")

print("联系8.7：专辑")
def make_album(name,zhuanji):
    info= {'name':name,'zhuanji':zhuanji}
    return info
a=make_album('panyueyun','tiantiantianlan')
b=make_album('zhanaijia','tongnian')
c=make_album('luodayou','hui')
print(f"{a},\n{b},\n{c}")

def make_album(name,zhuanji,number=None):
    info= {'name':name,'zhuanji':zhuanji}
    if number:
        info['number']=number
    return info
a=make_album('panyueyun','tiantiantianlan',5)
b=make_album('zhanaijia','tongnian',6)
c=make_album('luodayou','hui',9)
print(f"{a},\n{b},\n{c}")


print("联系8.8：用户的专辑")
def make_album(name,zhuanji,number=None):
    info= {'name':name,'zhuanji':zhuanji}
    if number:
        info['number']=number
    return info
while True:
    print("enter your name:")
    print("enter your zhuanji")
    print("enter a 'q' at any time to quit")
    name_1=input('name:')
    if name_1 == 'q':
        break
    zhuanji_1=input('zhuanji:')
    if zhuanji_1 == 'q':
        break
    number_1=input('number:')
    if number_1 == 'q':
        break
    make=make_album(name_1,zhuanji_1,number_1)
    print(make)

print("传递列表")
print("下面的示例将一个名字列表传递给一个名为greet_user()的函数，这个函数会向列表中的每个人发出问候")
def greet_user(names):
    """向列表中的每个用户发出问候"""
    for name in names:
        msg=f"hello,{name.title()}"
        print(msg)
usernames=['hannah','ty','margot']
greet_user(usernames)


usernames=['hannah','ty','margot']
def greet_user(names):
    """向列表中的每个用户发出问候"""
    msg=f"hello,{names.title()}"
    return msg
for name in usernames:
    username=greet_user(name)
    print(username)



print("在函数中修改列表")
print("不使用函数的情况下：需要打印的设计事先存储在一个列表中，打印后将其移到另一个列表中")
unprinted_designs=['phone case','robot pendant','dodecahedron']
completed_models=[]
"""
模拟打印每个设计，直到没有未打印的设计为止
打印每个设计后，都将其移到列表completed_models
"""
while unprinted_designs:
    current_design=unprinted_designs.pop()
    print(f"printting model:{current_design}")
    completed_models.append(current_design)
#显示打印好的模型
print("\nthe following models have been printed:")
for completed_design in completed_models:
    print(completed_design)

print("在使用两个函数的情况下")
def print_models(unprinted_designs_1,completed_models_1):
    """
    模拟打印每个设计，直到没有未打印的设计为止
    打印每个设计后，都将其移到列表completed_models
    """
    while unprinted_designs:
        current_design=unprinted_designs.pop()
        print(f"printing model:{current_design}")
        completed_models.append(current_design)
def show_completed_models(completed_models):
    """显示打印好的模型"""
    print(f"\nthe following models have been printed:")
    for completed_model in completed_models:
        print(completed_model)

unprinted_designs=['phone case','robot pendant','dodecahedron']
completed_models=[]

print_models(unprinted_designs,completed_models)
show_completed_models(completed_models)


print("禁止函数修改列表")
print("若需要保留原有的列表，传递时可使用列表的副本:如function_name(list[:])")
def print_models(unprinted_designs_1,completed_models_1):
    """
    模拟打印每个设计，直到没有未打印的设计为止
    打印每个设计后，都将其移到列表completed_models
    """
    while unprinted_designs_1:
        current_design=unprinted_designs_1.pop()
        print(f"printing model:{current_design}")
        completed_models.append(current_design)
def show_completed_models(completed_models_1):
    """显示打印好的模型"""
    print(f"\nthe following models have been printed:")
    for completed_model_1 in completed_models_1:
        print(completed_model_1)

unprinted_designs=['phone case','robot pendant','dodecahedron']
completed_models=[]

print_models(unprinted_designs[:],completed_models)
show_completed_models(completed_models)

print(unprinted_designs)
print(completed_models)


unprinted_designs=['phone case','robot pendant','dodecahedron']
completed_models=[]

print(unprinted_designs)
print(unprinted_designs[:])

unprinted_designs.append("acd")

print(unprinted_designs[:])
print(unprinted_designs)


print("练习8.9：消息")
lists=['potato','carrot','onion']
def show_messages(food_lists):
    show=f"i like eat {food_lists}"
    return show
for list in lists:
    show_message=show_messages(list)
    print(show_message)


lists=['potato','carrot','onion']
def show_messages(food_lists):
    for food_list in food_lists:
        print(f"i like eat {food_list}")
show_messages(lists)


print("练习8.10：发送消息")
lists=['potato','carrot','onion']
sent_messages=[]
def show_messages(list_a):
    while list_a:
        current_list=list_a.pop()
        print(f"i like eat {current_list}")
        sent_messages.append(current_list)
def send_messages(list_b):
    print(f"the following foods are :")
    for list in list_b:
        print(list)
show_messages(lists)
send_messages(sent_messages)

print(lists)
print(sent_messages)



print("练习8.11：消息归档")
lists=['potato','carrot','onion']
sent_messages=[]
def show_messages(list_a):
    while list_a:
        current_list=list_a.pop()
        print(f"i like eat {current_list}")
        sent_messages.append(current_list)
def send_messages(list_b):
    print(f"the following foods are :")
    for list in list_b:
        print(list)
show_messages(lists[:])
send_messages(sent_messages)

print(lists)
print(sent_messages)


print("传递任意数量的实参")
def make_pizza(*toppings):
    """
    *让python创建一个名为toppings的元组
    该元组包含函数收到的所有值
    """
    print(toppings)
make_pizza('pepperoni')
make_pizza('mushroonms','green peppers','extra cheese')

print("将函数调用print()替换为一个循环")
def make_pizza(*toppings):
    """概述要制作的披萨"""
    print("making a pizza with the following toppings:")
    for topping in toppings:
        print(f"-{topping}")
make_pizza('pepperoni')
make_pizza('mushroonms','green peppers','extra cheese')


print("结合使用位置实参和任意数量的实参")
print("如前面的函数还需要一个表示比萨尺寸的形参，必须将该形参放在*toppings的前面")
def make_pizza(size,*toppings):
    print(f"making a {size}-inch pizza with the following toppings:")
    for topping in toppings:
        print(f"-{topping}")
make_pizza(16,'pepperoni')
make_pizza(12,'mushroonms','green peppers','extra cheese')



print("使用任意数量的关键字实参")
def bulid_profile(first,last,**user_info):
    user_info["first_name"]=first
    user_info["last_name"]=last
    return user_info
user_profile=bulid_profile('albert','einstein',location='princeton',field='physics')
print(user_profile)

def bulid_profile(first,last,**user_info):
    user_info["first_name"]=first
    user_info["last_name"]=last
    print(user_info)
bulid_profile('albert','einstein',location='princeton',field='physics')


print("练习8.12：三明治")
def sandwich(*toppings):
    print(f"the following toppings of sandwich are:")
    for topping in toppings:
        print(f"-{topping}")
sandwich('bread','ham','turkey')
sandwich('bread','bacon','salami','swiss')
sandwich('bread','bacon','salami','swiss','lettuce')



print("练习8.13：用户简介")
def bulid_profile(first,last,**user_info):
    user_info["first_name"]=first
    user_info["last_name"]=last
    return user_info
user_profile=bulid_profile('zhang','san',like_food='noodle',age='25',country='china')
print(user_profile)

'''
print("练习8.14：汽车")
def car_info(manufacturer,model,**extra_info):
    extra_info["manufacturer"]=manufacturer
    extra_info["model"]=model
    return extra_info
car=car_info("subaru",'outback',color='blue',tow_package=True)
print(car)

def car_info(manufacturer,model,**extra_info):
    extra_info["manufacturer"]=manufacturer
    extra_info["model"]=model
    print(extra_info)
car_info("subaru",'outback',color='blue',tow_package=True)






